<template>
  <div class="container-big wing-blank ">
    <div v-if="showSearch" style="top:0px;max-height:80px;" class="screen-fixed-box top-search-box ">
      <div style=" position: relative;" class="top-search">
        <input @blur.prevent="initFun()" v-model.trim="search" maxlength="100" placeholder="请输入">
        <div class="top-search-img cenCen">
          <!-- <img src="https://gw.alicdn.com/tfs/TB1BhwLX7xz61VjSZFtXXaDSVXa-200-200.png"> -->
        </div>
      </div>
    </div>
    <div style="top:0px;max-height:80px;" class="screen-fixed-box">
      <div class="head-nav-box cenCen">
        <div @click="thisNav=false" :style="[{color: !thisNav?$store.state.themeColor:'#fff'}]" class="head-nav cenCen ">未激活 ({{unActive.length}}张)
          <div v-if="!thisNav" :style="[{ backgroundColor:$store.state.themeColor}]" class="borderBottom"></div>
        </div>
        <div @click="thisNav=true" :style="[{color: thisNav?$store.state.themeColor:'#fff'}]" class="head-nav  cenCen">已激活 ({{isActive.length}}张)
          <div v-if="thisNav" :style="[{ backgroundColor:$store.state.themeColor}]" class="borderBottom"></div>
        </div>
      </div>
    </div>
    <div style="padding-bottom: 336px; padding-top: 90px;" class="container">
      <div class="tian-nav-box cenBet">
        <div class="tian-state">
          <!-- 状态
          <img class="tian-state-img" src="https://gw.alicdn.com/tfs/TB1pQsSHmzqK1RjSZFHXXb3CpXa-200-200.png">
          <div class="tian-state-son-box">
            <div>已分享</div>
            <div>未分享</div>
          </div> -->
        </div>
        <!-- &&isActive.length 会出现如果没有找到则无法回去了 -->
        <div v-if="thisNav" class="tian-time cenBet ">
          <div :style="[{color:$store.state.themeColor}]">激活时间</div>
          <div @click="datepicker('activeStartDate')">{{activeStartDate?activeStartDate:'开始时间'}}</div>
          <div @click="datepicker('activeEndDate')">{{activeEndDate?activeEndDate:'结束时间'}}</div>
        </div>
        <!-- &&unActive.length -->
        <div v-if="!thisNav" class="tian-time cenBet ">
          <div :style="[{color:$store.state.themeColor}]">分享时间</div>
          <div @click="datepicker('shareStartTime')">{{shareStartTime?shareStartTime:'开始时间'}}</div>
          <div @click="datepicker('shareEndTime')">{{shareEndTime?shareEndTime:'结束时间'}}</div>
        </div>
      </div>
      <!-- @click.stop="goDetail(ticket)" -->
      <div v-if="thisNav" v-for="(ticket ,index) of  isActive" :key="index" class="buyTicket-box">
        <buyTicket :ticket="ticket" :isActive="1" :index="index"></buyTicket>
      </div>
      <!-- @click.stop="goDetail(ticket)" -->
      <div v-if="!thisNav" v-for="(ticket ,index) of  unActive" :key="index" class="buyTicket-box">
        <buyTicket :ticket="ticket" :isActive="0" :index="index"></buyTicket>
      </div>
    </div>
    <div style="bottom:0px;" :class="{'btn-box-bag':isActive.length>4||unActive.length>4}" class="screen-fixed-box ">
      <div class="btn-box cenBet">
        <div v-if="thisNav&&isActive.length" @click="ticketSelect()" :style="[{color:$store.state.themeColor}]" class="btn cenCen">
          <div :class="{'selThis':isActiveSelAll}" class="con-tit-sel  cenCen">
            <img v-if="isActiveSelAll" src="https://img.alicdn.com/tfs/TB1su6aa3aH3KVjSZFjXXcFWpXa-200-200.png">
          </div>
          全选
        </div>
        <div v-if="!thisNav&&unActive.length" @click="ticketSelect()" :style="[{color:$store.state.themeColor}]" class="btn cenCen">
          <div :class="{'selThis':unActiveSelAll}" class="con-tit-sel  cenCen">
            <img v-if="unActiveSelAll" src="https://img.alicdn.com/tfs/TB1su6aa3aH3KVjSZFjXXcFWpXa-200-200.png">
          </div>
          全选
        </div>
        <div v-if="!thisNav&&unActive.length" :style="[{color:$store.state.themeColor}]" class="btn btnRig cenCen">
          <div @click="callBackGroupTicketByIds()">
            重置激活码
          </div>
          <div @click="distribute()">
            分发
          </div>
        </div>
        <div v-if="thisNav&&isActive.length" :style="[{color:$store.state.themeColor}]" class="btn btnRig cenCen">
          <div @click="callBackGroupTicketByIds()">
            召回门票
          </div>
        </div>
      </div>
    </div>
    <bottomNav :class="{'navborder':isActive.length>4||unActive.length>4}"></bottomNav>
    <co-dialog :open="shareAlert">
      <div class="shareAlert-box cenBet ">
        <div :style="[{color:$store.state.themeColor}]" class="shareAlert-tit cenCen">
          <span>{{selectUnActive.inviteCodeLength}}</span>
          个激活码
        </div>
        <div class="share-con-box cenBet">
          <div v-for="(item,index) of selectUnActive.inviteCode" :key="index" class="share-con cenCen">
            <div :style="[{color:$store.state.themeColor}]" class="share-con">{{item.tTypeName}}</div>
            <!-- <div class="share-con">9月22日??</div> -->
            <div class="share-con"><span :style="[{color:$store.state.themeColor}]">{{item.inviteCodeList.length}}</span>
              个激活码</div>
          </div>
        </div>
        <div :style="[{color:$store.state.themeColor},{borderColor:$store.state.themeColor}]" class="shareAlert-input">
          <input :style="[{color:$store.state.themeColor}]" maxlength="20" v-model.trim="shareRemarks" placeholder="请输入备注">
        </div>
        <div class="shareAlert-btn cenCen">
          <div :style="[{color:$store.state.themeColor}]" @click="sureCopy()" class="cenCen">确定复制</div>
          <div @click="ddShare()" v-if="selectUnActive.inviteCodeLength==1" style="border-left: 1px solid  #fff;" :style="[{color:$store.state.themeColor},{borderColor:$store.state.themeColor}]" class="cenCen">分享</div>
          <div @click="shareAlert=false" style="border-left: 1px solid  #fff;color:#888" :style="[{borderColor:$store.state.themeColor}]" class="cenCen">取消</div>
        </div>
      </div>
    </co-dialog>
  </div>
</template>
<script>
import buyTicket from "./assembly/buyTicket";
import bottomNav from "./../bottomNav";
import service from "@/api/mine";
import ddApi from "./../ddApi.js";
import * as dd from "dingtalk-jsapi";

export default {
  components: {
    buyTicket,
    bottomNav
  },
  data() {
    return {
      shareAlert: false,
      activityId: "", //活动activityId
      showSearch: true, //展示搜索弹框
      search: "", //搜索的字段
      thisNav: false, //true 已激活
      isActive: [], //已激活门票列表
      isActiveSelAll: false, //已激活门票列表是否全选
      unActive: [], //未激活门票列表
      unActiveSelAll: false, //未激活门票列表是否全选,
      shareStartTime: "", //分享开始时间
      shareEndTime: "", //分享结束时间
      activeStartDate: "", //激活开始时间
      activeEndDate: "", //激活结束时间
      selectUnActive: {}, //选择未激活
      shareRemarks: "" //分享备注
    };
  },
  created() {
    this.activityId =
      this.getUrl("activityId") || sessionStorage.getItem("activityId") || ""; //23 52 53
    if (!this.activityId) {
      this.$toast("必要参数丢失");
      return;
    }
    sessionStorage.setItem("activityId", this.activityId);
    this.initFun();
  },
  methods: {
    // 获取url参数
    getUrl(parameter) {
      return (
        decodeURIComponent(
          (new RegExp("[?|&]" + parameter + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
          ) || [, ""])[1].replace(/\+/g, "%20")
        ) || ""
      );
    },
    async initFun() {
      console.log(this.search);
      // 分页查询团购票
      let subData = {
        activityId: this.activityId,
        start: 0,
        size: 1000000
      };
      if (this.search) {
        subData.keyWord = this.search;
      }
      if (this.shareStartTime) {
        subData.shareStartTime = new Date(this.shareStartTime).getTime();
      }
      if (this.shareEndTime) {
        subData.shareEndTime = new Date(this.shareEndTime).getTime();
      }
      if (this.activeStartDate) {
        subData.activeStartDate = new Date(this.activeStartDate).getTime();
      }
      if (this.activeEndDate) {
        subData.activeEndDate = new Date(this.activeEndDate).getTime();
      }

      if (
        subData.shareStartTime &&
        subData.shareEndTime &&
        subData.shareStartTime > subData.shareEndTime
      ) {
        this.$toast("分享开始时间不可大于结束时间");
        return;
      }
      if (
        subData.activeStartDate &&
        subData.activeEndDate &&
        subData.activeStartDate > subData.activeEndDate
      ) {
        this.$toast("激活开始时间不可大于结束时间");
        return;
      }

      if (
        subData.shareStartTime &&
        subData.shareEndTime &&
        subData.shareStartTime == subData.shareEndTime
      ) {
        subData.shareEndTime += 86400000;
      }
      if (
        subData.activeStartDate &&
        subData.activeEndDate &&
        subData.activeStartDate == subData.activeEndDate
      ) {
        subData.activeEndDate += 86400000;
      }

      if (this.thisNav) {
        delete subData.shareStartTime;
        delete subData.shareEndTime;
      } else {
        delete subData.activeStartDate;
        delete subData.activeEndDate;
      }
      this.$store.state.loading = true;
      service.queryGroupTicketByActivityForPagination(subData).then(
        res => {
          this.$store.state.loading = false;
          this.setMenu();
          this.showSearch = false;
          // isActive 0 未激活  1 已激活
          const { ticketList = [] } = res.result;
          this.isActive = [];
          this.unActive = [];
          for (let i = 0; i < ticketList.length; i++) {
            sessionStorage.setItem(
              "activityTitle",
              ticketList[i].activityTitle
            );
            this.$set(ticketList[i], "isSelect", false); //是否已经选上
            this.$set(ticketList[i], "isEdit", false); //是否可以编辑如编辑详情
            if (ticketList[i].isActive) {
              this.isActive.push(ticketList[i]);
            } else {
              this.unActive.push(ticketList[i]);
            }
          }
        },
        err => {
          this.$store.state.loading = false;
        }
      );
    },
    async setMenu() {
      let t = this;
      this.showSearch = !this.showSearch;
      dd.ready(function() {
        dd.biz.navigation.setRight({
          show: true, //控制按钮显示， true 显示， false 隐藏， 默认true
          control: true, //是否控制点击事件，true 控制，false 不控制， 默认false
          text: t.showSearch ? "取消搜索" : "搜索", //控制显示文本，空字符串表示显示默认文本
          onSuccess: function(result) {
            t.setMenu();
          },
          onFail: function(err) {}
        });
      });
    },
    async datepicker(who) {
      const res = await ddApi.datepicker();
      if (!res) {
        return;
      }
      if (who == "shareStartTime") {
        this.shareStartTime = res;
      }
      if (who == "shareEndTime") {
        this.shareEndTime = res;
      }
      if (who == "activeStartDate") {
        this.activeStartDate = res;
      }
      if (who == "activeEndDate") {
        this.activeEndDate = res;
      }
      this.initFun();
    },
    //整理数据
    checkInviteCode(ticketList) {
      let value = [];
      for (let i = 0; i < ticketList.length; i++) {
        let obj = {
          ...ticketList[i],
          inviteCodeList: []
        };
        for (let j = 0; j < ticketList.length; j++) {
          if (ticketList[i].ticketTypeId == ticketList[j].ticketTypeId) {
            obj.inviteCodeList.push({
              inviteCode: ticketList[j].inviteCode
            });
          }
        }
        value.push(obj);
      }

      let obj = {};
      value = value.reduce(function(item, next) {
        obj[next.ticketTypeId]
          ? ""
          : (obj[next.ticketTypeId] = true && item.push(next));
        return item;
      }, []);
      return new Promise(resolve => {
        resolve(value);
      });
    },
    // 确定复制
    async sureCopy() {
      if (!this.shareRemarks) {
        this.$toast("请输入备注");
        return;
      }
      let title = sessionStorage.getItem("activityTitle") || "大会活动";
      // ${this.selectUnActive.oldInviteCode[0].inviteCode}
      let url = `https://${document.domain}/isv_products_pay_sell_ticket/?activityId=${this.activityId}#/mine/activation`;
      let ticket = "";
      this.selectUnActive.inviteCode.map(item => {
        let itemText = item.tTypeName + ":";
        item.inviteCodeList.map(it => {
          itemText += it.inviteCode + ",";
        });
        ticket += "\n" + itemText;
      });
      let text = `邀请您参加${title}，请您尽快登录以下链接，提交激活码并进行门票激活。激活链接：${url} \n您的门票激活码如下：${ticket}\n感谢您对${title}的支持！`;
      console.log("text", text);
      const res = await ddApi.setData(text);
      this.$toast(res);
      this.batchRemarkGroupTicket();
    },
    // 备注
    async batchRemarkGroupTicket() {
      let ids = [];
      this.selectUnActive.oldInviteCode.map(item => {
        ids.push(item.ticketId);
      });
      const { success = false } = await service.batchRemarkGroupTicket({
        activityId: this.activityId,
        ids: ids,
        remark: this.shareRemarks
      });
      this.shareAlert = false;
      const res = await service.updateShareTime({
        activityId: this.activityId,
        ids
      });

      if (success) {
        this.initFun();
      }
    },
    // 分发
    async distribute() {
      let ticketList = [];
      let ids = [];
      this.unActive.map(item => {
        if (item.isSelect) {
          ids.push(item.ticketId);
          ticketList.push(item);
        }
      });
      if (!ticketList.length) {
        this.$toast("请选择");
        return;
      }
      let res = await this.checkInviteCode(ticketList);
      this.selectUnActive = {
        inviteCodeLength: ticketList.length,
        ids: ids,
        inviteCode: res, //整理以后的数据
        oldInviteCode: ticketList //没有整理的数据
      };
      this.shareAlert = true;
      console.log(this.selectUnActive);
    },
    // 钉钉分享
    async ddShare() {
      if (!this.shareRemarks) {
        this.$toast("请输入备注");
        return;
      }
      console.log(this.selectUnActive.oldInviteCode[0]);
      let url = `https://${document.domain}/isv_products_pay_sell_ticket/?inviteCode=${this.selectUnActive.oldInviteCode[0].inviteCode}&activityId=${this.activityId}#/mine/activation`;
      console.log("url", url);
      let title = sessionStorage.getItem("activityTitle") || "大会活动";
      console.log("title", title);
      let ticket = "";
      this.selectUnActive.oldInviteCode.map(item => {
        ticket += `${item.tTypeName}:${item.inviteCode}`;
      });
      console.log("ticket", ticket);

      let content = `邀请您参加${title},请您尽快登录以下链接，提交激活码并进行门票激活。激活链接：${url},您的门票激活码如下：${ticket},感谢您对${title}的支持！`;
      console.log("content", content);
      let image = "";
      console.log("image", image);
      let res = await ddApi.share(url, title, content, image);
      console.log(res);
      if (res == "ok") {
        // 提交备注
        this.batchRemarkGroupTicket();
      }
    },
    // 召回门票
    async callBackGroupTicketByIds() {
      let isSelect = [];
      if (this.thisNav) {
        this.isActive.map(item => {
          if (item.isSelect) {
            isSelect.push(item.ticketId);
          }
        });
      } else {
        this.unActive.map(item => {
          if (item.isSelect) {
            isSelect.push(item.ticketId);
          }
        });
      }

      if (!isSelect.length) {
        this.$toast("请选择");
        return;
      }
      if (isSelect.length > 10) {
        this.$toast("选择数量过多，至多只能选择10张");
        return;
      }
      const confirm = await this.$confirm(
        `您确定进行${this.thisNav ? "召回" : "重置"}`,
        {
          title: "温馨提示",
          okLabel: "确认",
          showCancel: true
        }
      );
      if (!confirm) {
        return;
      }
      this.$store.state.loading = true;
      service
        .callBackGroupTicketByIds({
          activityId: this.activityId,
          ids: isSelect
        })
        .then(
          res => {
            this.$store.state.loading = false;
            const { success = false } = res;
            if (success) {
              this.$toast(this.thisNav ? "成功召回" : "重置成功");
              this.initFun();
              this.unActiveSelAll = false;
              this.isActiveSelAll = false;
            }
          },
          err => {
            this.$store.state.loading = false;
          }
        );
    },
    //是否可以编辑如编辑详情
    isEdit(index) {
      if (this.thisNav) {
        this.isActive[index].isEdit = true;
      } else {
        this.unActive[index].isEdit = true;
      }
    },
    async editChange(index, ticketId, remark) {
      const { success = false } = await service.batchRemarkGroupTicket({
        activityId: this.activityId,
        ids: [ticketId],
        remark: remark
      });
      if (success) {
        // this.unActive[index].isEdit = false;
        this.$toast("备注成功");
      }
    },
    //门票选择who 谁调用的方法
    ticketSelect(who, index) {
      if (this.thisNav) {
        //激活的
        if (who == "son") {
          // 如果是子组件调用则直接取反值
          this.isActive[index].isSelect = !this.isActive[index].isSelect;
          this.isActiveSelAll = true;
          for (let i = 0; i < this.isActive.length; i++) {
            if (!this.isActive[i].isSelect) {
              this.isActiveSelAll = false;
              break;
            }
          }
        } else {
          this.isActiveSelAll = !this.isActiveSelAll;
          for (let i = 0; i < this.isActive.length; i++) {
            this.isActive[i].isSelect = this.isActiveSelAll;
          }
        }
      } else {
        // 未激活的
        if (who == "son") {
          // 如果是子组件调用则直接取反值
          this.unActive[index].isSelect = !this.unActive[index].isSelect;
          this.unActiveSelAll = true;
          for (let i = 0; i < this.unActive.length; i++) {
            if (!this.unActive[i].isSelect) {
              this.unActiveSelAll = false;
              break;
            }
          }
        } else {
          this.unActiveSelAll = !this.unActiveSelAll;
          for (let i = 0; i < this.unActive.length; i++) {
            this.unActive[i].isSelect = this.unActiveSelAll;
          }
        }
      }
    },
    // 查看详情
    goDetail(ticket) {
      this.$router.push({
        path: "/mine/ticket",
        query: {
          ticketId: ticket.ticketId,
          ticketTypeId: ticket.ticketTypeId,
          activityId: ticket.activityId,
          groupBuying: true
        }
      });
    },
    // =====
    focusIntoView(e) {
      const isAndroid =
        navigator.userAgent.toLowerCase().indexOf("android") !== -1;
      if (isAndroid) {
        this.timer = setTimeout(() => {
          e.target.scrollIntoView();
        }, 200);
      }
    }
  }
};
</script>

<style scoped>
.head-nav-box {
  width: 100%;
  height: 86px;
  background: rgb(49, 51, 57);
  border-bottom: 1px solid #4e4f54;
  z-index: 2;
}
.head-nav {
  width: 50%;
  height: 100%;
  font-size: 30px;
  color: #fff;
  position: relative;
  cursor: pointer;
}
.borderBottom {
  position: absolute;
  left: 0px;
  bottom: 0px;
  width: 30%;
  left: 35%;
  height: 2px;
}

.tian-nav-box {
  width: 100%;
  height: auto;
  margin-bottom: 26px;
}
.tian-state {
  width: 110px;
  width: 0px;
  height: auto;
  background-image: linear-gradient(-116deg, #3cb9ff 0%, #6044d4 100%);
  color: #fff;
  font-size: 26px;
  position: relative;
  /* border: 1px solid red; */
  cursor: pointer;
}
.tian-state-son-box {
  width: 100%;
  height: auto;
  position: absolute;
  bottom: 39px;
  left: 0px;
  z-index: 2;
}
.tian-state-son-box > div {
  width: 100%;
  height: auto;
  color: #fff;
  font-size: 26px;
}
.tian-state-img {
  width: 20px;
  transform: rotate(90deg);
  -ms-transform: rotate(90deg); /* IE 9 */
  -moz-transform: rotate(90deg); /* Firefox */
  -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
  -o-transform: rotate(90deg); /* Opera */
}
.tian-time {
  width: auto;
  height: auto;
}
.tian-time > div {
  width: auto;
  height: auto;
  color: #fff;
  font-size: 26px;
  padding-left: 20px;
}
.buyTicket-box {
  width: 100%;
  height: auto;
  padding: 0px;
  margin-top: 16px;
}
.btn-box {
  width: 100%;
  height: auto;
  padding: 18px;
  background: inherit;
  padding: 16px 48px 186px 48px;
}
.btn {
  width: auto;
  height: auto;
  font-size: 28px;
  cursor: pointer;
}
.btnRig > div {
  margin-left: 28px;
}
.con-tit-sel {
  width: 26px;
  height: 26px;
  border: 1px solid #636566;
  background: rgba(33, 35, 37, 0.3);
  font-size: 16px;
  color: #eeeeee;
  cursor: pointer;
  margin: 0px 16px 0px 2px;
}
.selThis {
  background-image: linear-gradient(-116deg, #3cb9ff 0%, #6044d4 100%);
  color: #fff !important;
  border: none;
}
.con-tit-sel > img {
  width: 70%;
  height: auto;
}
/*头部搜索 */
.top-search-box {
  z-index: 10;
}
.top-search {
  height: auto;
  min-height: 90px;
  background: rgb(49, 51, 57);
  padding: 16px 30px;
}
.top-search > input {
  width: 100%;
  font-size: 26px;
  color: #fff;
  padding: 16px 44px 16px 16px;
  background: #101112;
}
.top-search-img {
  position: absolute;
  top: 0px;
  right: 40px;
  width: 39px;
  height: 100%;
}
.top-search-img > img {
  width: 100%;
  height: auto;
}
.van-popup-box {
  width: 90%;
  height: auto;
  background: #fff;
  color: #000;
  border-radius: 10px;
}
.shareAlert-box {
  width: 100%;
  height: auto;
  min-height: 500px;
  /* border: 1px solid red; */
  position: relative;
  padding: 66px 0px 130px 0px;
  /* background: rgba(0, 0, 0, 1);
  border: 1px solid rgba(61, 61, 61, 0.8); */
}
.shareAlert-tit {
  width: 100%;
  height: auto;
  position: absolute;
  left: 0px;
  top: 0px;
  text-align: center;
  font-size: 30px;
}
.shareAlert-tit > span {
  font-weight: bold;
  font-size: 44px;
  margin-right: 10px;
}
.shareAlert-input {
  position: absolute;
  left: 0px;
  bottom: 56px;
  width: 100%;
  height: auto;
  border-bottom: 1px solid #fff;
}
.shareAlert-input > input {
  width: 100%;
  height: auto;
  text-align: left;
  font-size: 26px;
  padding: 16px 0px;
}
.shareAlert-btn {
  position: absolute;
  left: 0px;
  bottom: 0px;
  width: 100%;
  height: auto;
  /* border: 1px solid red; */
}
.shareAlert-btn > div {
  width: 50%;
  height: auto;
  /* border: 1px solid red; */
  font-size: 26px;
}
.share-con-box {
  width: 100%;
  height: auto;
  flex-wrap: wrap;
  max-height: 900px;
  overflow-y: auto;
}
.share-con {
  width: 100%;
  height: auto;
  font-size: 26px;
  margin-top: 6px;
}
.share-con > span {
  font-weight: bold;
  font-size: 28px;
}
.navborder {
  border-top: 1px solid #4e4f54;
}
.btn-box-bag {
  /* background: rgb(49, 51, 57, 0.9); */
  /* background: rgb(49, 51, 57); */
  background: rgba(0, 0, 0, 0.8);
}
</style>
